package org.uw.src.main;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Logger {
	private static final String INFO = " INFO: ";
	private static final String WARN = " WARNING: ";
	private static final String ERR  = " ERROR: ";
	private static final String Path = "log.txt";
	public static boolean logging = true;

	public static void print(String s) {
		log(getTime() + INFO +  s);
		System.out.println(getTime() + INFO +  s);
	}
	
	public static void warn(String s) {
		log(getTime() + WARN +  s);
		System.out.println(getTime() + WARN +  s);
	}
	
	public static void err(String s) {
		log(getTime() + ERR +  s);
		System.out.println(getTime() + ERR +  s);
	}
	
	public static void NoLogPrint(String s) {
		System.out.println(s);
	}
	
	private static String getTime() {
	    Date today = Calendar.getInstance().getTime();
	    SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss");
	    return formatter.format(today);
	}
	
	private static void log(String s) {
		File f = new File(Path);
		if(!f.exists()) CreateLogFile();
		
		if(logging){
			FileWriter fstream;
			try {
				fstream = new FileWriter(f, true);
				BufferedWriter out = new BufferedWriter(fstream);
				out.write(s);
				out.newLine();
				out.close();
			} catch (IOException e) {
				NoLogPrint("ERROR: Could not write to log");
			}
		}
	}
	
	private static void CreateLogFile() {
		File f = new File(Path);
			try {
				f.createNewFile();
				NoLogPrint("INFO:Created log file");
			} catch (IOException e) {
				logging = false;
				NoLogPrint("ERROR:Could not create log file");
			}
	}
	
}
